<?php

namespace app\admin\controller\department;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use fast\Tree;

/**
 *
 */
class Type extends Backend
{

    protected $relationSearch = true;
    protected $noNeedRight = ['selectpage'];

    /**
     */
    protected $model = null;
    protected $typeList;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\department\Type;

        $this->tree = Tree::instance();
        $this->tree->init($this->model->all(), 'pid');
        $this->typeList = $this->tree->getTreeList($this->tree->getTreeArrayPname(0));
        $this->view->assign("typeList", $this->typeList);

    }


    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            $searchValue = $this->request->request("searchValue");
            $search = $this->request->request("search");

            //构造父类select列表选项数据
            $list = [];
            if ($search||$searchValue) {

                foreach ($this->typeList as $k => &$v) {

                    if ($search&&stripos($v['name'], $search) !== false) {
                        $list[] = $v;
                    }
                    if ($searchValue&&in_array($v['id'], explode(',',$searchValue)) !== false) {
                        $v['name']=preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", " ", strip_tags($v['name'])); //过滤空格
                        $list[] = $v;
                    }
                }
            } else {
                $list = $this->typeList;
            }

            $list = array_values($list);

            foreach ($list as $k => &$v) {
                $v['name']=str_replace("&nbsp;", " ", strip_tags($v['name'])); //过滤空格
            }
            $total = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);

        }
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        $row = $this->model->get($ids);
        empty($row) && $this->error("未找到该类别");

        $childIds = $this->model::getChildrenIds($row['id'], true);
        foreach ($childIds as $val) {
            //检测是否已被绑定
            $where = [
                "type_id" => $val
            ];
            $exits = model("Admin")->where($where)->find();
            !empty($exits) && $this->error("该类别或下级类别已绑定用户，禁止删除");

            $exits = \app\admin\model\department\Article::where($where)->find();
            !empty($exits) && $this->error("该类别或下级类别已绑定项目，禁止删除");
        }


        parent::del($childIds);
    }

    public function excel()
    {
        if ($this->request->isPost()) {
            ini_set('memory_limit', '-1'); //设置为不限制
            set_time_limit(0);  //设置为不限制

            $fileName = input('pdf');
            $fileName = str_replace($_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"], '', $fileName);
            $file = $_SERVER ["DOCUMENT_ROOT"] . $fileName;
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
            $reader->setReadDataOnly(true);  //过滤excel中的特殊字符
            $PHPExcel = $reader->load($file);
            $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数
            $data = [];

            for ($row = 2; $row <= $highestRow; $row++) { //行号从1开始
                for ($column = 'A'; $column <= $highestColumn; $column++) { //列数是以A列开始
                    if (empty($sheet->getCell($column . $row)->getValue()) == false) {
                        $data[$row][$column] = $sheet->getCell($column . $row)->getValue();
                    }
                }
//                if (!isset($data[$row]['B'])) unset($data[$row]);
            }
//            halt($data);
            Db::startTrans();
            try {
                $typeArr = [];
                $j = 2;
                foreach ($data as $k => $v) {
                    $exits = $this->model->where('name', $v['A'])->value('id');
                    if (!empty($exits)) {
                        $this->error("第【{$j}】行的名称已存在，请删除后重试");
                    }
                    $j++;
                }
                foreach ($data as $k => $v) {
                    $res = [
                        "name" => $v['A'],

                    ];
                    $typeArr[] = $res;
                }
                $res = $this->model->saveAll($typeArr);

                Db::commit();
                $this->success();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
        $doc = "/template/excel/密级列表导入模板.xlsx";
        $this->view->assign("doc", $doc);
        return $this->view->fetch();
    }


    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        return $this->index();
//        return parent::selectpage();
    }

}
